package com.fansy.service.impl;

import java.io.File;
import org.apache.commons.io.FileUtils;

import com.fansy.service.UploadService;

public class UploadServiceImpl implements UploadService {
	
	@Override
	public String uploadFile(byte[] payload, String filePath) {
		File file = new File(filePath);
		if(file.exists()) {
			String filename = file.getName();
			String[] nameArray = filename.split("\\.");
			if(nameArray!=null&&nameArray.length==2) {
				nameArray[0] = 	nameArray[0] + Long.toString(System.currentTimeMillis());
				
				file = new File(file.getParentFile().getAbsolutePath() + "\\" + nameArray[0] + "." + nameArray[1]);
			} else if(nameArray!=null&&nameArray.length==1) {
				nameArray[0] = 	nameArray[0] + Long.toString(System.currentTimeMillis());
				file = new File(file.getParentFile().getAbsolutePath() + "\\" + nameArray[0]);
			} else {
				throw new RuntimeException("Invalid file " + file.getName());
			}
		}
		
		try {
			FileUtils.writeByteArrayToFile(file, payload);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			throw new RuntimeException("Fail to write file " + e.getMessage());			
		}
		
		return file.getName();
	}
	
	public static void main(String args[]) {
		UploadService up = new UploadServiceImpl();
		up.uploadFile("hello".getBytes(), "D:\\tmp\\a.txt");
		up.uploadFile("hello".getBytes(), "D:\\tmp\\a.txt");
		up.uploadFile("hello".getBytes(), "D:\\tmp\\a");
		up.uploadFile("hello".getBytes(), "D:\\tmp\\a");
	}

}
